package com.ruoyi.cems.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cems.domain.*;
import com.ruoyi.cems.service.ILanXinService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LanXinServiceImpl implements ILanXinService {

    @Value("${lxapi.appTokenUrl}")
    private String appTokenUrl;
    @Value("${lxapi.idMappingUrl}")
    private String idMappingUrl;
    @Value("${lxapi.messagesUrl}")
    private String messagesUrl;
    @Value("${lxapi.appId}")
    private String appId;
    @Value("${lxapi.secret}")
    private String secret;
    @Value("${lxapi.orgId}")
    private String orgId;
    @Value("${lxapi.idType}")
    private String idType;
    @Autowired
    private RedisCache redisCache;
    @Override
    public String fetchAppToken() {
        String appToken = redisCache.getCacheObject("lanxin_apptoken");
        if(StringUtils.isNotBlank(appToken)){
            log.info("蓝信从缓存中获取appToken：{}", appToken);
            //从redis缓存中获取appToken
            return appToken;
        }
        String url = appTokenUrl + "?grant_type=client_credential&appid={appId}&secret={secret}";

        RestTemplate restTemplate = RestTemplateUtil.getRestTemplateWithTrustAllSSL();
        ResponseEntity<AppTokenResponse> response = restTemplate.getForEntity(
                url,
                AppTokenResponse.class,
                appId,
                secret
        );

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            AppTokenResponse tokenResponse = response.getBody();
            if (tokenResponse.getErrCode() == 0) {
                log.info("蓝信从接口中获取appToken：{}", tokenResponse.getData().getAppToken());
                redisCache.setCacheObject("lanxin_apptoken", tokenResponse.getData().getAppToken(), tokenResponse.getData().getExpiresIn() - 200, TimeUnit.SECONDS);
                return tokenResponse.getData().getAppToken();
            } else {
                throw new RuntimeException("Error fetching token: " + tokenResponse.getErrMsg());
            }
        }

        throw new RuntimeException("Failed to fetch app token");
    }
    @Override
    public String fetchIdMapping(String idType, String idValue) {
        String url = idMappingUrl + "?app_token={appToken}&org_id={orgId}&id_type={idType}&id_value={idValue}";

        String appToken = fetchAppToken();
        RestTemplate restTemplate = RestTemplateUtil.getRestTemplateWithTrustAllSSL();
        ResponseEntity<String> response = restTemplate.getForEntity(
                url,
                String.class,
                appToken,
                orgId,
                idType,
                idValue
        );


        log.info("蓝信获取用户ID结果：{}", response.getBody());

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            String messageResponse = response.getBody();
            JSONObject jsonObject = JSON.parseObject(messageResponse);
            if (jsonObject.getInteger("errCode") == 0) {
                return jsonObject.getJSONObject("data").getString("staffId");
            } else {
                return null;
            }
        }

        return null;
    }

    @Override
    public String sendTextMessage(List<String> userCodeList, String content) {
        String url = messagesUrl + "?app_token=" + fetchAppToken();

        //根据用户编码获取用户ID
        List<String> userIdList = new ArrayList<>();
        for (String userCode : userCodeList){
            String userId = fetchIdMapping(idType, "86-" + userCode);
            if(StringUtils.isNotBlank(userId)){
                userIdList.add(userId);
            }
        }
        if(userIdList.isEmpty()){
            //没有用户不发送
            return null;
        }

        // 构建请求体
        SendMessageRequest request = new SendMessageRequest();
        request.setUserIdList(userIdList);
        request.setDepartmentIdList(null);
        request.setMsgType("text");

        // 构建消息内容
        MsgData msgData = new MsgData();
        TextContent textContent = new TextContent();
        textContent.setContent(content);
        msgData.setText(textContent);
        request.setMsgData(msgData);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建HTTP实体
        HttpEntity<SendMessageRequest> entity = new HttpEntity<>(request, headers);

        // 发送POST请求
        RestTemplate restTemplate = RestTemplateUtil.getRestTemplateWithTrustAllSSL();
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

        log.info("蓝信发送消息结果：{}", response.getBody());

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            String messageResponse = response.getBody();
            JSONObject jsonObject = JSON.parseObject(messageResponse);
            if (jsonObject.getInteger("errCode") == 0) {
                return messageResponse;
            } else {
                throw new RuntimeException("Error sending message: " + messageResponse);
            }
        }

        throw new RuntimeException("Failed to send message");
    }

    public String sendLinkCardMessage(List<String> userCodeList, String title, String link) {
        String url = messagesUrl + "?app_token=" + fetchAppToken();

        //根据用户编码获取用户ID
        List<String> userIdList = new ArrayList<>();
        for (String userCode : userCodeList){
            String userId = fetchIdMapping(idType, "86-" + userCode);
            if(StringUtils.isNotBlank(userId)){
                userIdList.add(userId);
            }
        }
        if(userIdList.isEmpty()){
            //没有用户不发送
            return null;
        }

        // 构建请求体
        SendMessageRequest request = new SendMessageRequest();
        request.setUserIdList(userIdList);
        request.setDepartmentIdList(null);
        request.setMsgType("linkCard");

        // 构建消息内容
        MsgData msgData = new MsgData();
        LinkCardContent linkCardContent = new LinkCardContent();
        linkCardContent.setTitle(title);
        linkCardContent.setLink(link);
        msgData.setLinkCard(linkCardContent);
        request.setMsgData(msgData);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建HTTP实体
        HttpEntity<SendMessageRequest> entity = new HttpEntity<>(request, headers);

        // 发送POST请求
        RestTemplate restTemplate = RestTemplateUtil.getRestTemplateWithTrustAllSSL();
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

        log.info("蓝信发送消息结果：{}", response.getBody());

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            String messageResponse = response.getBody();
            JSONObject jsonObject = JSON.parseObject(messageResponse);
            if (jsonObject.getInteger("errCode") == 0) {
                return messageResponse;
            } else {
                throw new RuntimeException("Error sending message: " + messageResponse);
            }
        }

        throw new RuntimeException("Failed to send message");
    }
}
